<template>
  <div id="app" style="width: 85vw;">
    <div class="content-header">
      <h1>功能管理<small>车次调度</small></h1>
      <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>功能管理</el-breadcrumb-item>
        <el-breadcrumb-item>车次调度</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="app-container">
  <div class="box">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="queryParams.queryString"
          placeholder="请输入调度编号或司机姓名"
          style="width: 200px"
          @keyup.enter="handleQuery"
          clearable
      >
        <template #append>
          <el-button @click="handleQuery">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">新增调度</el-button>
      <el-button @click="resetQuery">重置</el-button>
      <el-button type="success" @click="handleDownload">下载模板</el-button>
      <el-upload action="/api/admin/checi/upload"
                 name="file"
                 :headers="headerObj"
                 :show-file-list="false"
                 :on-success="handleSuccess"
                 :before-upload="beforeUpload">
        <el-button type="primary">上传文件</el-button>
      </el-upload>
    </div>


    <!-- 数据表格 -->
    <el-table
        :data="dispatchList"
        border
        style="width: 100%"
        v-loading="loading"
        highlight-current-row
        stripe
    >
      <el-table-column prop="dispatchId" label="调度编号" width="85" />
      <el-table-column prop="routeId" label="线路编号" width="85" />
      <el-table-column prop="tripId" label="车次编号" width="85" />
      <el-table-column prop="dispatchTime" label="调度时间" width="163">
        <template #default="scope">
          {{ formatDateTime(scope.row.dispatchTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="expectedDepartureTime" label="预计发车时间" width="163">
        <template #default="scope">
          {{ formatDateTime(scope.row.expectedDepartureTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="actualDepartureTime" label="实际发车时间" width="163">
        <template #default="scope">
          {{ formatDateTime(scope.row.actualDepartureTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="adjustedExpectedArrivalTime" label="预计到达时间" width="163">
        <template #default="scope">
          {{ formatDateTime(scope.row.adjustedExpectedArrivalTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="vehicleId" label="车辆编号" width="85" />
      <el-table-column prop="driverId" label="司机编号" width="85" />
      <el-table-column prop="driverName" label="司机姓名" width="85" />
      <el-table-column prop="dispatchStatus" label="调度状态" width="85">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.dispatchStatus)">
            {{ scope.row.dispatchStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="dispatchReason" label="调度原因" width="100" show-overflow-tooltip />
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="queryParams.currentPage"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="dialog.title"
        v-model="dialog.visible"
        width="700px"
        @close="resetForm"
        destroy-on-close
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="调度编号" prop="dispatchId">
              <el-input v-model="form.dispatchId" placeholder="请输入调度编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线路编号" prop="routeId">
              <el-input v-model="form.routeId" placeholder="请输入线路编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车次编号" prop="tripId">
              <el-input v-model="form.tripId" placeholder="请输入车次编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="调度时间" prop="dispatchTime">
              <el-date-picker
                  v-model="form.dispatchTime"

                  type="datetime"
                  placeholder="选择调度时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计发车时间" prop="expectedDepartureTime">
              <el-date-picker
                  v-model="form.expectedDepartureTime"
                  type="datetime"
                  placeholder="选择预计发车时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际发车时间" prop="actualDepartureTime">
              <el-date-picker
                  v-model="form.actualDepartureTime"
                  type="datetime"
                  placeholder="选择实际发车时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调整后到达时间" prop="adjustedExpectedArrivalTime">
              <el-date-picker
                  v-model="form.adjustedExpectedArrivalTime"
                  type="datetime"
                  placeholder="选择调整后到达时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车辆编号" prop="vehicleId">
              <el-input v-model="form.vehicleId" placeholder="请输入车辆编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机编号" prop="driverId">
              <el-input v-model="form.driverId" placeholder="请输入司机编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="司机姓名" prop="driverName">
              <el-input v-model="form.driverName" placeholder="请输入司机姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调度状态" prop="dispatchStatus">
              <el-select v-model="form.dispatchStatus" placeholder="请选择调度状态" style="width: 100%">
                <el-option label="已调度" value="已调度" />
                <el-option label="调度中" value="调度中" />
                <el-option label="取消调度" value="取消调度" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="调度原因" prop="dispatchReason">
          <el-input
              v-model="form.dispatchReason"
              type="textarea"
              rows="3"
              placeholder="请输入调度原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>
  </div>
    </div>
  </div>
</template>
<style scoped>
.schedule-manage {
  margin-top: 20px; /* 设置距离顶部的间距 */
}

/*  */
</style>
<script setup>

import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import request from '@/util/http'

// 查询参数
const queryParams = reactive({
  queryString: '',
  currentPage: 1,
  pageSize: 10
})

// 数据相关
const loading = ref(false)
const submitLoading = ref(false)
const dispatchList = ref([])
const total = ref(0)
const formRef = ref(null)

// 对话框数据
const dialog = reactive({
  visible: false,
  title: '',
  type: 'add'
})

// 表单数据
const form = reactive({
  dispatchId: undefined,
  routeId: '',
  tripId: '',
  dispatchTime: null,
  expectedDepartureTime: null,
  actualDepartureTime: null,
  adjustedExpectedArrivalTime: null,
  vehicleId: '',
  driverId: '',
  driverName: '',
  dispatchStatus: '',
  dispatchReason: ''
})

// 表单验证规则
const rules = {
  routeId: [{ required: true, message: '请输入线路编号', trigger: 'blur' }],
  tripId: [{ required: true, message: '请输入车次编号', trigger: 'blur' }],
  expectedDepartureTime: [{ required: true, message: '请选择预计发车时间', trigger: 'change' }],
  vehicleId: [{ required: true, message: '请输入车辆编号', trigger: 'blur' }],
  driverId: [{ required: true, message: '请输入司机编号', trigger: 'blur' }],
  driverName: [{ required: true, message: '请输入司机姓名', trigger: 'blur' }],
  dispatchStatus: [{ required: true, message: '请选择调度状态', trigger: 'change' }]
}

// API请求方法
const api = {
  getList: (params) => request.get('/admin/checi/findPage', { params }),
  add: (data) => request.post('/admin/checi/add', data),
  update: (data) => request.put('/admin/checi/update', data),
  delete: (id) => request.delete(`/admin/checi/${id}`),
  download: () => request.get('/admin/checi/download', { responseType: 'blob' })
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    '已调度': 'success',
    '调度中': 'warning',
    '取消调度': 'danger'
  }
  return statusMap[status] || 'info'
}

//上传之前进行文件格式校验
// 校验文件格式
// 上传之前进行文件格式校验
const beforeUpload = async (file) => {
  try {
    const isXLS = file.type === 'application/vnd.ms-excel';
    if (isXLS) {
      ElMessage.success('上传成功！');  // 添加格式校验通过的提示
      return true;
    }
    const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (isXLSX) {
      ElMessage.success('上传成功！');  // 添加格式校验通过的提示
      return true;
    }
    ElMessage.error('上传文件只能是xls或者xlsx格式!');
    return false;
  } catch (error) {
    console.error('文件格式校验失败:', error);
    ElMessage.error('文件格式校验失败');
    return false;
  }
}

// 上传成功提示
// const handleSuccess = async (response, file) => {
//   try {
//     if (response.flag) {
//       ElMessage({
//         message: `文件上传成功！${response.message}`, // 显示上传成功的提示信息
//         type: 'success',
//       });
//       // 初始化日历组件数据
//       await initData(formatDate(currentYear, currentMonth, 1));
//     } else {
//       ElMessage.error(`上传失败：${response.message}`); // 显示上传失败的提示信息
//     }
//   } catch (error) {
//     console.error('上传成功处理失败:', error);
//     ElMessage.error('上传成功处理失败');
//   }
// }


// 下载模板
const handleDownload = async () => {
  try {
    const response = await api.download()
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'diaodu.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 查询数据
const handleQuery = async () => {
  loading.value = true
  try {
    const { data } = await api.getList(queryParams)
    if (data.flag) {
      dispatchList.value = data.data.records
      total.value = data.data.total
    } else {
      ElMessage.error(data.message)
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryParams.queryString = ''
  handleQuery()
}

// 新增按钮
const handleAdd = () => {
  resetForm()
  dialog.type = 'add'
  dialog.title = '新增调度'
  dialog.visible = true
}

// 编辑按钮
const handleEdit = (row) => {
  dialog.type = 'edit'
  dialog.title = '编辑调度'
  Object.assign(form, row)
  dialog.visible = true
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该调度记录吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      const { data } = await api.delete(row.dispatchId)
      if (data.flag) {
        ElMessage.success('删除成功')
        handleQuery()
      } else {
        ElMessage.error(data.message)
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const apiMethod = dialog.type === 'add' ? api.add : api.update
        const { data } = await apiMethod(form)
        if (data.flag) {
          ElMessage.success(dialog.type === 'add' ? '新增成功' : '修改成功')
          dialog.visible = false
          handleQuery()
        } else {
          ElMessage.error(data.message)
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    dispatchId: undefined,
    routeId: '',
    tripId: '',
    dispatchTime: null,
    expectedDepartureTime: null,
    actualDepartureTime: null,
    adjustedExpectedArrivalTime: null,
    vehicleId: '',
    driverId: '',
    driverName: '',
    dispatchStatus: '',
    dispatchReason: ''
  })
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.currentPage = val
  handleQuery()
}

// 日期时间格式化
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 初始化
onMounted(() => {
  handleQuery()
})
</script>

<style scoped>
.dispatch-manage {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}
</style>